package com.sapp.imagecolorization.utils

import android.app.Activity
import android.content.ClipboardManager
import android.content.Context
import android.content.Context.CLIPBOARD_SERVICE
import android.content.Context.LAYOUT_INFLATER_SERVICE
import android.net.Uri
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import com.sapp.imagecolorization.R
import com.sapp.imagecolorization.retrofit.RestApiService
import com.squareup.picasso.Picasso
import me.relex.photodraweeview.PhotoDraweeView


class Utils {

    fun showToastMessage(context: Context, text: String) {
        Toast.makeText(context, text, Toast.LENGTH_LONG).show()
    }

    fun loadImageFromUrl(context: Activity, imageLink: String, imageView: PhotoDraweeView) {
        try {
           // Picasso.get().load(imageLink).into(imageView)
            imageView.setPhotoUri(Uri.parse(imageLink))
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
            showToastMessage(context, context.getString(R.string.wrong_image_link))

        }
    }

    fun showLinkPopup(
        context: Activity,
        layout: LinearLayout,
        imageView: PhotoDraweeView,
        progressBar: ProgressBar,
        restApiService: RestApiService
    ) {

        val inflater = context.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater?
        val popupView = inflater!!.inflate(R.layout.paste_link_popup_window, null)

        val width = LinearLayout.LayoutParams.WRAP_CONTENT
        val height = LinearLayout.LayoutParams.WRAP_CONTENT
        val focusable = true // lets taps outside the popup also dismiss it
        val popupWindow = PopupWindow(popupView, width, height, focusable)

        popupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0)
        showToastMessage(context, "The text copied from clipboard")

        val link: EditText = popupView.findViewById(R.id.link_field)

        link.setTextIsSelectable(true)
        link.isFocusable = true
        link.isFocusableInTouchMode = true

        val cancel = popupView.findViewById(R.id.cancel_link_selection) as Button
        cancel.setOnClickListener {
            popupWindow.dismiss()

        }

        val clipboard: ClipboardManager? =
            context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager?
        if (clipboard!!.text != null) {
            val clipText = clipboard.text
            link.setText(clipText.toString())

        }

        val confirm = popupView.findViewById(R.id.confirm_link_selection) as Button
        confirm.setOnClickListener {
            progressBar.visibility = View.VISIBLE
            restApiService.loadUrlImage(
                context,
                link.text.toString().trim(),
                imageView,
                progressBar
            )
            popupWindow.dismiss()

        }

        popupView.setOnClickListener {
            popupWindow.dismiss()
        }

    }
}